<!--
 * @Author: weidewei
 * @Date: 2025-11-12 10:12:32
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-12 14:50:26
 * @Description: 
 * @FilePath: \2025-front-face\review-knowledge\20251112\复习手写Promise A+规范.html
-->
<script>
  const PENDING = "pending";
  const FULFILLED = "fulfilled";
  const REJECTED = "rejected";

  function isPromise(obj) {
    return !!(obj && typeof obj === "object" && typeof obj.then === "function");
  }

  function runMicroTask(callback) {
    if(MutationObserver) {
        const div = document.createElement("div");
        const observer = new MutationObserver(callback);
        observer.observe(div,{
            childList: true
        });
        div.innerHTML = '111';
    }else if(process && process.nextTick) {
        process.nextTick(callback);
    }else {
        setTimeout(callback,0);
    }
  }

  class MyPromise {
    #state;
    #value;
    #handlers;
    constructor(excutor) {
      this.#state = PENDING;
      this.#value = undefined;
      // 存放队列
      this.#handlers = [];
      try {
        excutor(this.#resove.bind(this), this.#reject.bind(this));
      } catch (err) {
        console.log("err", err);
        this.#reject(err);
      }
    }

    // 放入微任务队列中 包括执行器函数，状态，Promise成功的函数，Promise失败的函数
    #pushHandler(excutor, state, resolve, reject) {
      this.#handlers.push({
        excutor,
        state,
        resolve,
        reject,
      });
    }

    #runHandlers() {
        if (this.#state === PENDING) return;
        while(this.#handlers[0]) {
           const handler =  this.#handlers[0];
           this.#runOneHandler(handler);
           this.#handlers.shift(); 
        }
    }

    #runOneHandler({excutor,state,resolve,reject}) {
      runMicroTask(()=>{
        if(state !== this.#state) return;
        if (typeof excutor !== "function") {
          // 传递后续处理并非一个函数，要进行状态穿透
          this.#state === FULFILLED
            ? resolve(this.#value)
            : reject(this.#value);
          return;
        }
        try{
           const result = excutor(this.#value);
          if (isPromise(result)) {
            result.then(resolve, reject);
          } else {
            // 如果是前一个then有返回值,就传给下一个then
            resolve(result);
          }
        }catch(err) {
           reject(err); 
        }
      })
    }


    then(onFulfilled, onRejected) {
      return new MyPromise((resolve, reject) => {
        this.#pushHandler(onFulfilled, FULFILLED, resolve, reject);
        this.#pushHandler(onRejected, REJECTED, resolve, reject);
        this.#runHandlers();
      });
    }

    #resove(data) {
      this.#setState(FULFILLED, data);
    }

    #reject(reason) {
      this.#setState(REJECTED, reason);
    }

    // 改变状态
    #setState(state, value) {
      if (this.#state !== PENDING) return;
      this.#state = state;
      this.#value = value;
      this.#runHandlers();
    }
  }

  const p = new MyPromise((resolve, reject) => {
    resolve(1);
  }).then(data=>{
    return new MyPromise((resolve,reject)=>{
        resolve(111);
    });
  }).then(data1=>{
    console.log('data1',data1)
  });
  console.log("p", p);
// console.log(1);
// setTimeout(()=>{
//     console.log(2);
// });
// runMicroTask(()=>{
//     console.log(3);
// })
</script>
